<template>
  <a-tree-select
    v-bind="getAttrs"
    :treeData="getOptions"
    @change="handleChange"
    @search="handleSearch"
    :field-names="fieldNames"
  >
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
    <template #suffixIcon v-if="loading">
      <LoadingOutlined spin />
    </template>
  </a-tree-select>
</template>

<script lang="ts">
  import {
    type PropType,
    computed,
    defineComponent,
    watch,
    ref,
    onMounted,
    unref,
    nextTick,
  } from 'vue';
  import { TreeSelect } from 'ant-design-vue';
  import { isEmpty, isArray, isFunction } from '/@/utils/is';
  import { get } from 'lodash-es';
  import { propTypes } from '/@/utils/propTypes';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  import { useDebounceFn } from '@vueuse/core';
  import { sleep } from '/@/utils';
  export default defineComponent({
    name: 'ApiTreeSelect',
    components: { ATreeSelect: TreeSelect, LoadingOutlined },
    props: {
      api: { type: Function as PropType<(arg?: Recordable<any>) => Promise<Recordable<any>>> },
      params: { type: Object },
      treeData: { type: Array as PropType<Recordable<any>[]> },
      immediate: { type: Boolean, default: true },
      showSearch: { type: Boolean, default: false },
      isModelForm: propTypes.bool.def(false),
      formValues: propTypes.object.def({}),
      linkFields: propTypes.array.def([]),
      resultField: propTypes.string.def(''),
      labelField: propTypes.string.def('label'),
      valueField: propTypes.string.def('value'),
      childrenField: propTypes.string.def('children'),
    },
    emits: ['options-change', 'change', 'search'],
    setup(props, { attrs, emit }) {
      const treeData = ref<Recordable<any>[]>(props.treeData || []);
      const isFirstLoaded = ref<Boolean>(true);
      const loading = ref(false);
      const getAttrs = computed(() => {
        const { showSearch } = props;
        return {
          ...(props.api ? { treeData: unref(treeData) } : {}),
          ...attrs,
          showSearch,
        };
      });
      const getOptions = computed(() => treeData.value);

      const linkOn = computed(() => {
        const obj = {};

        props.linkFields.forEach((field: string) => {
          if (props.formValues.values && props.formValues.values[field]) {
            obj[field] = props.formValues.values[field];
          }
        });
        return obj;
      });

      const fieldNames = {
        children: props.childrenField,
        value: props.valueField,
        label: props.labelField,
      };

      function handleChange(...args) {
        emit('change', ...args);
      }

      const handleSearch = useDebounceFn(async function (text) {
        emit('search', text);
        await sleep(100);
        fetch(text);
      }, 200);

      watch(
        () => props.immediate,
        (v) => {
          v && !isFirstLoaded.value && fetch();
        },
      );
      watch(
        () => props.treeData,
        (v) => {
          v && !isFirstLoaded.value && fetch();
        },
      );

      watch(
        () => linkOn.value,
        async (v) => {
          await nextTick();

          !isEmpty(v) && fetch();
        },
        { deep: true },
      );
      onMounted(() => {
        props.immediate && fetch();
      });

      async function fetch(content = '') {
        const { api } = props;
        if (!api || !isFunction(api)) {
          treeData.value = props.treeData || [];
          return;
        }
        loading.value = true;
        treeData.value = [];
        let result;
        try {
          const params: Indexable = {
            ...linkOn.value,
            ...props.params,
          };
          if (props.isModelForm) {
            params.content = content;
          }
          result = await api(params);
        } catch (e) {
          console.error(e);
        }
        loading.value = false;
        if (!result) return;
        if (!isArray(result)) {
          result = get(result, props.resultField);
        }

        treeData.value = (result as Recordable<any>[]) || [];

        isFirstLoaded.value = false;

        emit('options-change', treeData.value);
      }
      return { getAttrs, loading, handleChange, handleSearch, fieldNames, getOptions };
    },
  });
</script>
